
// 实现根据radio控件切换对应页面
const loginRadio = document.getElementById('loginRadio');
const registerRadio = document.getElementById('registerRadio');
const loginSection = document.getElementById('loginSection');
const registerSection = document.getElementById('registerSection');

// 邮箱验证正则表达式
const emailRegex = /^[a-zA-Z0-9]+([._%+-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+$/;

// Radio切换事件
loginRadio.addEventListener('change', function() {
    if (this.checked) {
        loginSection.style.display = 'block';
        registerSection.style.display = 'none';
    }
});

registerRadio.addEventListener('change', function() {
    if (this.checked) {
        loginSection.style.display = 'none';
        registerSection.style.display = 'block';
    }
});

// 初始化页面状态
if (loginRadio.checked) {
    loginSection.style.display = 'block';
    registerSection.style.display = 'none';
}

// 通用消息提示函数 - 使用新的消息系统
function showMessage(message, duration = 2000) {
    if (window.messageUtils) {
        window.messageUtils.info(message, duration);
    } else {
        // 降级处理：如果消息系统未加载，使用原生alert
        console.warn('消息系统未加载，使用alert降级处理');
        alert(message);
    }
}

// 通用请求封装，自动带上 token
async function apiRequest(url, options = {}) {
    const token = localStorage.getItem("token");

    const headers = {
        'Content-Type': 'application/json',
        ...(options.headers || {})
    };

    if (token) {
        headers['Authorization'] = token;
    }

    const response = await fetch(url, {
        ...options,
        headers
    });

    // 401 表示未登录或 token 失效
    if (response.status === 401) {
        if (window.messageUtils) {
            window.messageUtils.error("登录已过期，请重新登录！");
        } else {
            showMessage("登录已过期，请重新登录！");
        }
        localStorage.removeItem("token");
        window.location.href = "/index.html";
        return;
    }

    return response.json();
}

// 引入API配置
// 注意：确保在HTML中先引入config.js
// <script src="/js/config.js"></script>

// 登录功能
document.querySelector('#loginSection .button').addEventListener('click', async () => {
    console.log('登录按钮点击');
    const email = document.getElementById('email').value.trim();
    const password = document.getElementById('password').value.trim();

    // 使用验证工具库进行表单验证
    if (!window.validationUtils) {
        showMessage('验证工具未加载，请刷新页面重试！');
        return;
    }

    // 定义验证规则
    const validationRules = {
        email: {
            required: true,
            type: 'email',
            label: '邮箱'
        },
        password: {
            required: true,
            type: 'password',
            minLength: 6,
            maxLength: 20,
            label: '密码'
        }
    };

    // 执行验证
    const formData = { email, password };
    const validationResult = window.validationUtils.validateForm(formData, validationRules);

    if (!validationResult.valid) {
        if (window.messageUtils) {
            window.messageUtils.error(validationResult.message);
        } else {
            showMessage(validationResult.message);
        }
        return;
    }

    try {
        // 使用统一的API配置
        const loginUrl = typeof getApiUrl !== 'undefined' ? 
            getApiUrl(API_CONFIG.ENDPOINTS.USER.LOGIN) : 
            "http://localhost:8080/user/login";
            
        const response = await fetch(loginUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                password: password
            })
        });

        const data = await response.json();

        if (response.ok && data.code === 200) {
            const token = data.data.token;
            const isAdmin = data.data.isAdmin;
            const status = data.data.status;
            if(status===false){
                if (window.messageUtils) {
                    window.messageUtils.error('用户被禁用！请联系管理员！');
                } else {
                    showMessage('用户被禁用！请联系管理员！');
                }
                return;
            }

            // 保存 token 到 localStorage
            localStorage.setItem("token", token);

            if (window.messageUtils) {
                window.messageUtils.success("登录成功！");
            } else {
                showMessage("登录成功！");
            }

            // 跳转逻辑
            if (isAdmin) {
                window.location.href = "/admin/dashboard.html";
            } else {
                window.location.href = "/user/home.html";
            }

        } else {
            const errorMsg = '登录失败：' + (data.msg || '服务器返回异常');
            if (window.messageUtils) {
                window.messageUtils.error(errorMsg);
            } else {
                showMessage(errorMsg);
            }
        }

    } catch (error) {
        console.error('登录异常:', error);
        if (window.messageUtils) {
            window.messageUtils.error('登录时发生错误！');
        } else {
            showMessage('登录时发生错误！');
        }
    }
});

// 注册按钮事件监听
document.querySelector('#registerSection .button').addEventListener('click', async function(e) {
    console.log('注册按钮点击');
    e.preventDefault(); // 防止表单默认提交行为
    await handleRegister();
});

// 处理注册逻辑
async function handleRegister() {
    const email = document.getElementById('regEmail').value.trim();
    const password = document.getElementById('regPassword').value.trim();
    const confirmPassword = document.getElementById('regConfirmPassword').value.trim();

    // 使用验证工具库进行表单验证
    if (!window.validationUtils) {
        showMessage('验证工具未加载，请刷新页面重试！');
        return;
    }

    // 定义验证规则
    const validationRules = {
        email: {
            required: true,
            type: 'email',
            label: '邮箱'
        },
        password: {
            required: true,
            type: 'password',
            minLength: 6,
            maxLength: 20,
            label: '密码'
        },
        confirmPassword: {
            required: true,
            label: '确认密码',
            custom: function(value) {
                if (value !== password) {
                    return '两次密码不一致！';
                }
                return true;
            }
        }
    };

    // 执行验证
    const formData = { email, password, confirmPassword };
    const validationResult = window.validationUtils.validateForm(formData, validationRules);

    if (!validationResult.valid) {
        if (window.messageUtils) {
            window.messageUtils.error(validationResult.message);
        } else {
            showMessage(validationResult.message);
        }
        return;
    }

    try {
        // 使用统一的API配置
        const registerUrl = typeof getApiUrl !== 'undefined' ? 
            getApiUrl(API_CONFIG.ENDPOINTS.USER.REGISTER) : 
            "http://localhost:8080/user/register";
            
        const response = await fetch(registerUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                password: password
            })
        });

        const data = await response.json();

        if (response.ok && data.code === 200) {
            if (window.messageUtils) {
                window.messageUtils.success('注册成功，请登录！');
            } else {
                showMessage('注册成功，请登录！');
            }
            // 自动切换到登录界面
            setTimeout(() => {
                loginRadio.checked = true;
                loginSection.style.display = 'block';
                registerSection.style.display = 'none';
                // 清空注册表单
                document.getElementById('regEmail').value = '';
                document.getElementById('regPassword').value = '';
                document.getElementById('regConfirmPassword').value = '';
            }, 1500);
        } else {
            const errorMsg = '注册失败：' + (data.msg || '服务器返回异常');
            if (window.messageUtils) {
                window.messageUtils.error(errorMsg);
            } else {
                showMessage(errorMsg);
            }
        }

    } catch (error) {
        console.error('注册异常:', error);
        if (window.messageUtils) {
            window.messageUtils.error('注册时发生错误！');
        } else {
            showMessage('注册时发生错误！');
        }
    }
}